#pragma once

// 允许把声明和实现写在一起
// .hpp 文件是无法形成库的，即便形成了库，也只是开源式的给别人，所以在很多开源项目里会用到

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <unistd.h>

#define TaskNum 3

typedef void (* task_t) ();  // 定义函数指针类型 task_t

task_t tasks[TaskNum];

void Print()
{
    std::cout << "This is the Print task!" << std::endl;
}
void DownLoad()
{
    std::cout << "This is the DownLoad task!" << std::endl;
}
void Flush()
{
    std::cout << "This is the Flush task!" << std::endl;
}

void LoadTask()
{
    srand(time(nullptr) ^ getpid() ^ 17777);
    tasks[0] = Print;
    tasks[1] = DownLoad;
    tasks[2] = Flush;
}

void ExcuteTask(int number)
{
    if (number > 3 || number < 0) return;
    tasks[number]();
}

int SelectTask()
{
    return rand() % TaskNum;
}


void work()
{
    while (true)
    {
        int command = 0;
        int n = read(0, &command, sizeof(command));
        if (n == sizeof(int))
        {
            std::cout << "The pid is " << getpid() << " handler task" << std::endl;
            ExcuteTask(command);
        }
        else if (n == 0)
        {
            std::cout << "sub process: " << getpid() << " quit" << std::endl;
            break;
        }
    }
}